package com.goldcn.interceptor;

import com.goldcn.common.HttpUtil;
import com.goldcn.common.exception.ServiceException;
import com.goldcn.common.model.DataResult;
import com.goldcn.common.util.CommonUtils;
import com.goldcn.config.ProConstants;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author Tim Peng
 * @version V1.0
 * @Description:借货开关拦截
 * @date 2017-5-10 13:52:32
 */
@Aspect
@Component
public class BorrowAspect {
    @Autowired
    RestTemplate restTemplate;

    private Logger logger = Logger.getLogger(getClass());

    @Pointcut("execution(public * com.goldcn.orderborrow..*.*(..))")
    public void checkSw(){}


    @Before("checkSw()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURI();
        if(CommonUtils.isNotEmpty(url) && url.indexOf("orderborrow/erp") != -1){
            return;
        }
        String ret=getBorrowSW(SystemContext.getCompanyID());
        if(!"2".equals(ret)){
            logger.info("########借货功能已关闭########");
            throw new ServiceException("该功能已关闭...");
        }
    }

    /**
     * 获取借货功能开关
     * @param companyID
     * @return
     */
    private String getBorrowSW(Long companyID){
        DataResult result = HttpUtil.httpGet(
                ProConstants.getOrderBorrowSW + companyID, restTemplate);
        return result.getIsSuccess() == 1?result.getData().toString():"";
    }
}
